package com.iot08.admin.service;

import com.iot08.admin.utils.ExcelUtil;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.entity.app.Device;
import com.iot08.common.entity.app.DeviceImsi;
import com.iot08.common.response.Response;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

/**
 * @version 1.0
 * @Description:
 * @time: 2020/10/20 14:59
 * @author: Rock
 */
@Slf4j
@Service
public class DeviceImsiService {

    @Resource(name = "appMongoTemplate")
    private MongoTemplate mongoTemplate;
    @Resource
    private DeviceService deviceService;

    @Value("${device.import.path: }")
    private String importPath;

    /**
     * @param id
     * @time: 2020/10/20 15:26
     * @author: Rock
     * @version 1.0
     */
    public DeviceImsi getById(String id) {
        return mongoTemplate.findById(id, DeviceImsi.class);
    }

    /**
     * @param warn
     * @time: 2020/10/20 15:04
     * @author: Rock
     * @version 1.0
     */
    public List<DeviceImsi> listByWarn(Integer warn) {
        return mongoTemplate.find(new Query(Criteria.where("warn").is(warn)), DeviceImsi.class);
    }

    /**
     * @param imei
     * @time: 2020/10/20 15:55
     * @author: Rock
     * @version 1.0
     */
    public Response<Object> searchImsi(String imei, SysUser user) {
        Device device = deviceService.findById(imei);
        if (device == null) {
            return Response.failedResponse("设备号不存在");
        }
        DeviceImsi di = getById(imei);
        if (di == null) {
            return Response.failedResponse(String.format("设备号：( %s )不存在imsi", imei));
        }
        if (user.getType() == Const.CHANNELUSER_TYPE) {
            return Response.failedResponse("无权限操作");
        }
        List<String> msgList = new ArrayList<>();
        if (StringUtil.isNotBlank(device.getIccid())) {
            msgList.add("设备iccid : " + device.getIccid());
        } else {
            msgList.add("设备iccid : 暂无");
        }
        msgList.add(String.format("imei:%s 的imsi如下：", imei));
        if (di.getImsi() != null) {
            for (Map.Entry<String, Object> entry : di.getImsi().entrySet()) {
                if (entry.getValue() instanceof Date) {
                    Date value = (Date) entry.getValue();
                    DateUtil.hanldeMongoDate(value, 2);
                    msgList.add(String.format("     imsi:%s, 时间为：%s", entry.getKey(), DateUtil.dateToStr(value, DateUtil.FORMAT_1)));
                }
            }
        }
        return Response.successResponse(msgList);
    }

    /**
     * @param
     * @time: 2020/10/20 17:55
     * @author: Rock
     * @version 1.0
     */
    public Response<Object> exportImsi(SysUser user) throws Exception {
        List<DeviceImsi> list = listByWarn(1);
        if (list == null || list.size() == 0) {
            return Response.failedResponse("重复设备号 imei 不存在");
        }
        if (user.getType() == Const.CHANNELUSER_TYPE) {
            return Response.failedResponse("无权限操作");
        }
        Workbook imsiExcel = new XSSFWorkbook();
        Sheet foundSheet = imsiExcel.createSheet("repetition_imsi");
        Row row = null;
        Cell cell = null;
        row = foundSheet.createRow(0);
        cell = row.createCell(0);
        ExcelUtil.setCellValue(cell, "imei");
        cell = row.createCell(1);
        ExcelUtil.setCellValue(cell, "imsi");
        cell = row.createCell(2);
        ExcelUtil.setCellValue(cell, "时间");

        int rowNum = 1;
        int cellNum = 0;
        for (DeviceImsi di : list) {
            boolean flag = true;
            for (Map.Entry<String, Object> entry : di.getImsi().entrySet()) {
                if (entry.getValue() instanceof Date == false) {
                    continue;
                }
                Date value = (Date) entry.getValue();
                DateUtil.hanldeMongoDate(value, 2);
                row = foundSheet.getRow(rowNum);
                if (row == null) {
                    row = foundSheet.createRow(rowNum);
                }
                if (flag) {
                    cell = row.createCell(cellNum + 0);
                    ExcelUtil.setCellValue(cell, di.getId());
                    flag = false;
                }
                cell = row.createCell(cellNum + 1);
                ExcelUtil.setCellValue(cell, entry.getKey());
                cell = row.createCell(cellNum + 2);
                ExcelUtil.setCellValue(cell, DateUtil.dateToStr(value, DateUtil.FORMAT_1));
                rowNum++;
                //防止超过Excel最多行数
                if (rowNum % 60000 == 0) {
                    rowNum = 1;
                    cellNum += 4;
                    row = foundSheet.getRow(0);
                    cell = row.createCell(cellNum);
                    ExcelUtil.setCellValue(cell, "imei");
                    cell = row.createCell(cellNum + 1);
                    ExcelUtil.setCellValue(cell, "imsi");
                    cell = row.createCell(cellNum + 2);
                    ExcelUtil.setCellValue(cell, "时间");
                }
            }
        }
        String exportExcelUrl = importPath + File.separator + "repetition_imsi.xlsx";
        FileOutputStream foundFile = new FileOutputStream(exportExcelUrl);
        imsiExcel.write(foundFile);
        foundFile.close();
        Map<String, Object> map = new HashMap<>();
        map.put("msg", String.format("重复设备号 imei有(%s)个，已经存储在 repetition_imsi.xlsx文件中，请下载查看", list.size()));
        map.put("exportExcelUrl", exportExcelUrl);
        return Response.successResponse(map);
    }
}
